package com.czk.stream;

import org.junit.Test;

import java.util.Optional;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/7/12 15:25
 */
public class IntStreamDemo {
    /**
     *
     */
    @Test
    public void fun_1() {
        // 计算综合
        int sum = IntStream.rangeClosed(1, 10).filter(x -> x % 2 == 0).sum();
        System.out.println(sum);
    }

    /**
     *
     */
    @Test
    public void fun_2() {
        // 不包含最后一个元素
        int sum = IntStream.range(1, 2).sum();
        System.out.println(sum);
    }

    @Test
    public void fun_3() {
        IntStream intStream = IntStream.builder().add(1).add(2).build();
        intStream.forEach(x -> System.out.println(x));
    }

    @Test
    public void fun_4() {
        IntStream intStream = IntStream.of(1);
        IntStream intStream1 = IntStream.of(2);
        IntStream concat = IntStream.concat(intStream, intStream1);
        concat.forEach(System.out::println);
    }

    /**
     * 利用规约求和
     */
    @Test
    public void fun_5() {
        Optional<Integer> reduce = Stream.of(1, 2, 3).reduce(Integer::sum);
        if (reduce.isPresent()) {
            System.out.println(reduce.get());
        }
    }

    @Test
    public void fun_6() {
        // 制定一个初始值
        Integer reduce = Stream.of(1, 2, 3).reduce(4, Integer::sum);
        System.out.println(reduce);
    }
}
